package com.xtayfjpk.zookeeper.test.master_workers.callback.master;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.data.Stat;

import com.xtayfjpk.zookeeper.test.master_workers.Master;
import com.xtayfjpk.zookeeper.test.master_workers.Master.MasterStates;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseDataCallback;

public class MasterCheckCallback extends BaseDataCallback {
	private static final Logger LOGGER = Logger.getLogger(MasterCheckCallback.class);
	private Master master;
	
	public MasterCheckCallback(Master master) {
		this.master = master;
	}


	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		master.checkMaster();
	}
	
	@Override
	protected void noNodeCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		/**
		 * 如果/master节点不存在，则继续竞争成为master
		 */
		master.runForMaster();
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, byte[] data,
			Stat stat) {
		if(master.getServerId().equals(new String(data))) {
			master.setState(MasterStates.ELECTED);
			master.takeLeadership();
		} else {
			master.setState(MasterStates.NOTELECTED);
			master.exists();
		}
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx,
			byte[] data, Stat stat) {
		LOGGER.error("Error when reading data.", 
                KeeperException.create(Code.get(rc), path)); 
	}
}
